/* Copyright 2009 Palm, Inc.  All rights reserved. */

var PincodeAssistant = Class.create({
		keyMap: $H({
		69:'1',
		82:'2',
		84:'3',
		68:'4',
		70:'5',
		71:'6',
		88:'7',
		67:'8',
		86:'9',
		64:'0',
	}),

	// keys with opt
	keyMapOpt: $H({
		49:'1',
		50:'2',
		51:'3',
		52:'4',
		53:'5',
		54:'6',
		55:'7',
		56:'8',
		57:'9',
		48:'0',
	}),

    initialize: function(params){//dialogTitle, msg,  hasCancelButton, type, /*callback,*/ number){
		this.params =params;
        this.enteredPin = [];
		this.currentPage = 1;
		this.number=params.number;
		this.closeapp=params.closeapp;
		this.maxLength = params.maxLength || 8;
    },
    
    setup: function() {
		if(this.params.callingapp == 'firstuse'){
			this.bodyClassName = this.controller.document.body.className;
			this.controller.document.body.className = "firstuse"
			$('done_pc').removeClassName('halfleft')
		}
		else {
			this.bodyClassName = this.controller.document.body.className;
			this.controller.document.body.className="appclass";
		}

        this.dsAttributes = {
			modelProperty: 'pin',
		};
		this.pinModel = {
		    'pin': '',
			disabled: true
		};
		this.controller.setupWidget('pinfield', this.dsAttributes, this.pinModel);
		this.controller.listen('pinfield', Mojo.Event.propertyChange, this.pinChangeHandler.bind(this));

		if(this.params.title)
        	this.controller.get('dialog_title').innerHTML = this.params.title[0];
		else
			this.controller.get('dialog_title').innerHTML = '';
		if(this.params.msg)
			this.controller.get('msg').innerHTML = this.params.msg[0];
		else
			this.controller.get('msg').innerHTML = '';
        this.controller.get('done_pc').addEventListener(Mojo.Event.tap, this.doDone.bindAsEventListener(this));
        if (this.params.callingapp == 'firstuse') {
			this.controller.get('firstuse_emergency').addEventListener(Mojo.Event.tap, this.doEmergency.bindAsEventListener(this));
			this.controller.get('emergency_pc').hide();
			this.controller.get('done_pc').removeClassName("half");
		}
		else {
			this.controller.get('emergency_pc').addEventListener(Mojo.Event.tap, this.doEmergency.bindAsEventListener(this));
			this.controller.get('firstuse_emergency').hide();
		}
		// bind to dialpad number buttons
        var number_buttons = this.controller.get('numbers_pincode').select('div');
        for (var i = 0; i < number_buttons.length; i++) {
			var button = number_buttons[i];
			var key = "";
			var prefix = button.id.match(/^(.*)_button_pincode$/);
			if (!prefix) 
				continue;
			switch (prefix[1]) {
				case "one":{
					key = '1';
				}
break;
				case "two":{
					key = '2';
				}
break;
				case "three":{
					key = '3';
				}
break;
				case "four":{
					key = '4';
				}
break;
				case "five":{
					key = '5';
				}
break;
				case "six":{
					key = '6';
				}
break;
				case "seven":{
					key = '7';
				}
break;
				case "eight":{
					key = '8';
				}
break;
				case "nine":{
					key = '9';
				}
break;
				case "zero":{
					key = '0';
				}
break;
				default:
					{
					
					}
			}
			button.observe('mousedown', this.numberClick.bindAsEventListener(this, key));
		}
        this.controller.get('delete_button').observe(Mojo.Event.tap, this.back.bindAsEventListener(this));
		this.controller.listen(this.controller.sceneElement, Mojo.Event.keydown, this.handleKeyDown.bind(this));

    },
	cleanup:function(){
		this.controller.document.body.className=this.bodyClassName;
	},
    handleKeyDown: function(event){
		var evt = event.originalEvent;
		if (evt.keyCode == Mojo.Char.backspace ||evt.keyCode == Mojo.Char.deleteKey) {
			var len =this.pinModel.pin.length; 
			if ( len > 0) {
				this.pinModel.pin = this.pinModel.pin.slice(0, len - 1)
				this.controller.modelChanged(this.pinModel, this);
			}
		} else if (evt.keyCode == Mojo.Char.enter) {
			this.doDone();
		}else{ 
			var c = this.translateKey(evt.keyCode);
			if(c && this.pinModel.pin.length < this.maxLength) {
				this.pinModel.pin = this.pinModel.pin + c;
				this.controller.modelChanged(this.pinModel, this);			
			}
		}
	},
	translateKey: function(keycode) {
		return this.keyMapOpt.get(keycode) || this.keyMap.get(keycode);
	},
	numberClick:function(event, key){
		if(this.currentPage < 3 && this.pinModel.pin.length ==0){
			if(this.params.title)
	        	this.controller.get('dialog_title').innerHTML = this.params.title[this.currentPage-1];
			if(this.params.msg)
				this.controller.get('msg').innerHTML = this.params.msg[this.currentPage-1];
			else
				this.controller.get('msg').innerHTML = '';
	
		}		

		if (key && this.pinModel.pin.length < this.maxLength) {
			this.pinModel.pin = this.pinModel.pin+key;
			this.controller.modelChanged(this.pinModel, this);
		}
	},
	back: function(event){
		var len =this.pinModel.pin.length; 
		if(len>0){
			this.pinModel.pin=this.pinModel.pin.slice(0,len-1)
			this.controller.modelChanged(this.pinModel, this);
		}
	},
	doCancel: function(){
		if (this.closeapp) {
			this.controller.window.close();
		}
		else {
			this.controller.stageController.popScene("pincode");
		}
	},
	doEmergency: function(){
        var request = new Mojo.Service.Request("palm://com.palm.applicationManager/open", {
            parameters: {
                id: 'com.palm.app.phone',
                params: {
                    "action": 'emergency',
					"locale": Mojo.Locale.current
                }
            }
        });

	},
    doDone: function(){
		// ignore presses when no number has been entered
		if (!this.pinModel.pin || this.pinModel.pin.length < 0) {
			return;
		}
		
		this.enteredPin[this.currentPage-1] = this.pinModel.pin;
		
		if ((this.currentPage == this.params.pinPages && this.currentPage>1)&& this.enteredPin[1]!==this.enteredPin[2]){
        	var firstpin=this.enteredPin[0];
			this.clearForm();
			this.enteredPin[0]=firstpin;
	        this.controller.get('msg').innerHTML = $L("PIN doesn't match");
			this.currentPage = 2;
			if(this.params.title)
        		this.controller.get('dialog_title').innerHTML = this.params.title[this.currentPage-1];
			return
		}
				
		if(this.currentPage == this.params.pinPages){
			this.params.callbackHandler(this.verifyPin.bind(this), this.enteredPin);
		}
		else{
			this.currentPage=this.currentPage+1;
			if(this.params.title && this.params.title[this.currentPage-1])
	        	this.controller.get('dialog_title').innerHTML = this.params.title[this.currentPage-1];
			if(this.params.msg && this.params.msg[this.currentPage-1])
				this.controller.get('msg').innerHTML = this.params.msg[this.currentPage-1];
			this.pinModel.pin='';
			this.controller.modelChanged(this.pinModel,this);
		}
    },
    
    verifyPin: function(isPinCorrect, errorString, title){
		Mojo.Log.info("PinCodeAssistant::verifyPin isPinCorrect:	"+isPinCorrect+" errorString:"+errorString);
        if (isPinCorrect) {
			if (errorString !== "no dial" && this.number) {
				PrefSetter.dial(this.number);
			}
			if (this.closeapp) {
				this.controller.window.close();
			}
			else {
				this.controller.stageController.popScene("pincode");
			}
	    }
        else if(errorString=='simlocked'){
			this.controller.get('dialog_title').innerHTML = $L("Contact carrier for new SIM");
			this.controller.get('msg').innerHTML = "&nbsp;";
			this.controller.get('panel').hide();
		}
		else {
            Mojo.Log.info("PIN Doesn't match " + this.enteredPin);
            this.clearForm();
            if(errorString)
				this.controller.get('msg').innerHTML = errorString;
			this.currentPage = 1;
			if(title)
    	    	this.controller.get('dialog_title').innerHTML = title
	    	else
		    	this.controller.get('dialog_title').innerHTML = $L("PIN incorrect");

        }
    },
    
    clearForm: function(){
		this.pinModel.pin='';
		this.controller.modelChanged(this.pinModel,this);
        this.enteredPin = [];
    },
	handlePUKParams:function(params, pintype){
		this.params =params;
		var message = '';
		if (pintype !== 2) {
			message = $L('Contact carrier for PUK code');
		} else {
			message = $L('Contact carrier for PUK2 code')
		}
		this.controller.get('dialog_title').innerHTML = $L('PIN incorrect');
		this.controller.get('msg').innerHTML = message;
	},
	pinChangeHandler: function(event){
		if(this.currentPage <3 && event.value.length == 1){
			if(this.params.title)
	        	this.controller.get('dialog_title').innerHTML = this.params.title[this.currentPage-1];
			if(this.params.msg)
				this.controller.get('msg').innerHTML = this.params.msg[this.currentPage-1];
			else
				this.controller.get('msg').innerHTML = '';
		}		
		//check if pin numerical only
		for (var i=0; i< this.pinModel.pin.length; i++){
			if (this.pinModel.pin.charAt(i)>'9' || this.pinModel.pin.charAt(i)<'0')
				
			this.pinModel.pin = this.pinModel.pin.slice(0, i)
			this.controller.modelChanged(this.pinModel, this);
		}

	},
	handleCommand: function(event){
		if (event.type == Mojo.Event.back && PalmSystem.isMinimal == true) {
			event.stopPropagation();
			Event.stop(event);
		}
	},
});
